#include <sstream>
#include "common.h"
#include "cJSON.h"



/**
 * 将json解析成CMessage
 *  
 {
	"name":"plugin",
	"command":"restart",
	"args": {
		"jsBundle":"blabla",
		"deviceType":"blabla"
	}
 }
 */ 
CMessage CMessage::parseJson(const std::string& json){
    CMessage msg;
    std::map<std::string,std::string> &argsMap = msg.args;
    cJSON *root = NULL;
    cJSON *name = NULL;
    cJSON *command = NULL;
    cJSON *args = NULL;
    cJSON *child = NULL;
    root = cJSON_Parse(json.data());
    if (!root) {
        return msg;
    }   
    name = cJSON_GetObjectItem(root, "name");
    if (!name) {
        return msg;
    }
    msg.name = name->valuestring;

    command = cJSON_GetObjectItem(root, "command");
    if (!command) {
        return msg;
    }
    msg.command = command->valuestring;

    args = cJSON_GetObjectItem(root, "args");
    if (!args) {
        return msg;
    }

    child = args->child;
    while(child != NULL){
        std::string key = child->string;
        std::string value = child->valuestring;
        std::cout << "key:" << key << ",value" << value << std::endl;
        msg.args.insert(std::make_pair(key,value));
        child = child->next;
    }

    cJSON_Delete(root);
    return std::move(msg);
}

std::string CMessage::toString() {
    cJSON * root =  cJSON_CreateObject();
    cJSON_AddItemToObject(root, "name", cJSON_CreateString(this->name.c_str()));
    cJSON_AddItemToObject(root, "command", cJSON_CreateString(this->command.c_str()));
    cJSON *args = cJSON_CreateObject();
    for(auto arg:this->args){
        cJSON_AddItemToObject(args, arg.first.c_str(), cJSON_CreateString(arg.second.c_str()));
    }
    cJSON_AddItemToObject(root, "args", args);
    std::string result = cJSON_Print(root);
    cJSON_Delete(root);
    return result;
}


bool ReadFileContent(const char* pFilePath, std::ios_base::openmode mode,std::string& strContent) {
    std::ostringstream buf;
    strContent.clear();
    std::ifstream infile;
    char ch;
    infile.open(pFilePath, mode);
    if(!infile.is_open()) {
        std::cout << "Open file failure!" << std::endl;
        return false;
    }
    while (buf && infile.get(ch)) {
        buf.put(ch);
    }
    strContent = buf.str();

    return true;
}

/**
 * 对于带bom头的utf8字符串,删除bom头
 */ 
std::string TrimUTF8BOM(const std::string& msg) {
    // trim utf8 bom
    std::size_t ret = msg.find_first_of("\xef\xbb\xbf");
	if(ret != std::string::npos){
		return msg.substr(3);
	}else{
        return msg;
    }
} 